/**
 * 病种入组病例管理初始化
 */
var SdsFillByDoctor = {
    id: "SdsFillByDoctorTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    hospID: null,
    checkPerm: $("#checkPerm").val(), // 审核权限
    submitPerm: '1', // 填报权限
    docUpPerm: $("#formCheckType").val(), // 医生能否直接上报配置
    enableIPQC: $("#enableIPQC").val(), // 是否启用过程质控
    docName:null,
    entityArray: [],
    statusMap: $.parseJSON($("#statusMap").val())
};

/**
 * 初始化表格的列
 */
SdsFillByDoctor.initColumn = function () {
    return [
        {
            width: 45, align: "center", valign: 'middle', sortable: true, formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize = $('#SdsFillByDoctorTable').bootstrapTable('getOptions').pageSize;
                //获取当前是第几页
                var pageNumber = $('#SdsFillByDoctorTable').bootstrapTable('getOptions').pageNumber;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        },
        {
            field: 'selectItem', checkbox: true, formatter: function (value, row, index) {
                if (SdsFillByDoctor.docUpPerm === "Y") {
                    if (row.state != 'Submit' && row.state != 'Check') {
                        return {
                            disabled: true
                        }
                    } else {
                        return {
                            disabled: false
                        }
                    }
                } else {
                    if (row.state != 'Check') {
                        return {
                            disabled: true
                        }
                    } else {
                        return {
                            disabled: false
                        }
                    }
                }

            }
        },
        /*{title: '单病种', field: 'entityId', width:200, align: 'center', valign: 'middle'},*/
        {title: '病案号', field: 'mrNum', width: 80, align: 'center', valign: 'middle', formatter:function (value,row,index) {
                // 设置该列鼠标悬浮显示系统内就诊号，方便查找调试
                var span=document.createElement('span');
                span.setAttribute('title',row.episodeId);
                span.innerHTML = value;
                return span.outerHTML;
            }},
        {title: '患者姓名', field: 'name', width: 80, align: 'center', valign: 'middle'},
        {title:'表单填充率',field:'eCount',width: 92,align:'center',
            formatter: function (value, row) {
                var tempval = ((parseInt(row.ECount) * 100) / (parseInt(row.ECount) + parseInt(row.NCount))).toFixed(1);
                if (isNaN(tempval)) tempval = 0
                if (tempval>100) tempval = 100.0;
                var htmlstr = '<div class="hisui-tooltip" title="' + tempval + '%" style="width:100%; height:20px;border:1px solid #B2BBBE;border-radius: 5px;position: relative;">' +
                    '<div style="width: ' + tempval + '%; height:18px;line-height: 18px;background-color:#50c878;color:#FFFFFF;border-radius: 4px;">' +tempval + '%</div></div>';
                return htmlstr;
            }
        },
        {
            title: '迟报天数',
            field: 'reportDelayDays',
            width: 92,
            align: 'center',
            valign: 'middle',
            formatter: function (value, row, index) {
                if (7 <= value && value < 10) {
                    return "<div style='background-color:#0099CC;color: #FFFFFF'>" + value + "</div>";
                } else if (10 <= value && value < 30) {
                    return "<div style='background-color:#ffd500;color: #FFFFFF'>" + value + "</div>";
                } else if (30 <= value && value < 90) {
                    return "<div style='background-color:#FF9900;color: #FFFFFF'>" + value + "</div>";
                } else if (90 <= value) {
                    return "<div style='background-color:#CC0066;color: #FFFFFF'>" + value + "</div>";
                } else {
                    return "<div style='background-color:#66CCCC;color: #FFFFFF'>" + value + "</div>";
                }
            }
        },
        {title: '科室', field: 'admLocDesc', width: 80, align: 'center', valign: 'middle'},
        {title: '主管医师', field: 'admDoctorName', width: 80, align: 'center', valign: 'middle',sortable: true},
        {title: '主要诊断', field: 'reason', width: 90, align: 'center', valign: 'middle', sortable: true},
        {title: '出院日期', field: 'dishDate', width: 160, align: 'center', valign: 'middle', sortable: true},
        {
            title: '填报状态',
            field: 'state',
            width: 80,
            align: 'center',
            valign: 'middle',
            formatter: function (value, row, index) {
                row.stateDesc = "";
                if (row.reportState === 2) {
                    row.stateDesc = "上报成功";
                    return "<div title='"+ row.reportMsg+"' style='color: #50c878;cursor: pointer; '>上报成功</>";
                } else if (row.reportState === 4){
                    row.stateDesc = "上报失败";
                    return "<div title='"+ row.reportMsg+"' style='color:#ff461f;cursor: pointer;' >上报失败</>";
                } else {
                    row.stateDesc = SdsFillByDoctor.statusMap[value];
                    if (row.stateDesc.indexOf("失败") > -1||row.stateDesc.indexOf("退回") > -1) {
                        return "<div style='color:#ff461f;cursor: pointer;' >" + row.stateDesc + "</>";
                    } else {
                        return "<div>" + row.stateDesc + "</>";
                    }
                }
            }
        },
        // {title: '入院日期', field: 'admDate', width: 120, align: 'center', valign: 'middle',sortable: true},
        // {title: '出院日期', field: 'dishDate', width: 120, align: 'center', valign: 'middle',sortable: true},
        // {title: '入单日期', field: 'inDate', width: 120, align: 'center', valign: 'middle',sortable: true},
        {
            title: '操作',
            field: 'id',
            align: 'center',
            width: '120px',
            valign: 'middle',
            formatter: function (value, row, index) {
                var _html = '<a href="javascript:SdsFillByDoctor.edit(\'' + row.episodeId + '\',\'' + row.id + '\',\''+row.name+'\',\''+row.mrNum+'\',\''+row.dishDate+'\',\''+row.stateDesc+'\')" title="填报"><i class="hisui-icon icon-write-order"></i></a>';
                if (row.state != 'Up') {
                    _html += '<a href="javascript:SdsFillByDoctor.del(\'' + row.id + '\',\'' + row.entityId +'\')" title="排除"><i class="hisui-icon icon-cancel"></i></a>';
                }
                // if (SdsFillByDoctor.docUpPerm === 'Y') {
                //     _html += '<a href="javascript:SdsFillByDoctor.upload(\'' + row.id + '\')" title="上报"><i class="hisui-icon icon-upload-cloud"></i></a>';
                // }
                _html += '<a href="javascript:SdsFillByDoctor.record(\'' + row.id + '\',\'' + row.mrNum + '\',\'' + row.name + '\')" title="日志"><i class="hisui-icon icon-clock-record"></i></a>';
                return _html;
            }
        }];
};

SdsFillByDoctor.loadTableData = function (searchType, startDate, endDate, entityId, status) {
    var queryData = {};
    queryData['searchType'] = searchType;
    queryData['startDate'] = startDate;
    queryData['endDate'] = endDate;
    queryData['entityId'] = entityId;
    queryData['status'] = status;
    queryData['locId'] = $("#locId").val();
    queryData['docName']=SdsFillByDoctor.docName;
    SdsFillByDoctor.table.refresh({query: queryData, pageNumber: 1});
    //默认展示全院待填报情况
    SdsFillByDoctor.docName="";
};

/**
 * 检查是否选中
 */
SdsFillByDoctor.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        layer.msg("请先选中表格中的某一记录！");
        return false;
    } else {
        SdsFillByDoctor.seItem = selected[0];
        return true;
    }
};

/**
 * 打开查看病种入组病例详情
 */
SdsFillByDoctor.edit = function (episodeId, id,name,mrNum,dishDate,stateDesc)  {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        // 未启用过程质控模块直接打开填报表单
        if (SdsFillByDoctor.enableIPQC == 'Y') {
            SdsFillByDoctor.GetMrListIfo(episodeId, id, name, mrNum, dishDate, stateDesc);
        } else {
            SdsFillByDoctor.openFormWin(id, name, mrNum, dishDate, stateDesc);
        }
    }
};

/**
 * 删除病种入组病例
 */
SdsFillByDoctor.del = function (id,entityId) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        entityId = this.seItem.entityId
        flag = true;
    }
    if (flag) {
        var index = layer.open({
            type: 2,
            title: ['排除单病种【信息录入】'],
            area: ['600px', '400px'],
            zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
            content: "/sds/sdsqcformshow/excludereason?mrListId=" + id + "&entityId=" + entityId + "&execUser=" + encodeURIComponent($("#userName").val()),
            skin: 'layer-ext-hisui',
            scrollbar: false//为了禁止父页面滚动条滚动
        });
        //监听子页面的postMessage
        function receiveMessage(event) {
            //取得子页面传回来的值
            if (event.data == "close") {
                // 如果传回close，关闭当前弹窗
                layer.close(index);
            }
            if (event.data == "save") {
                SdsFillByDoctor.table.refresh();
                setTimeout(function () {
                    layer.close(index);
                }, 1000);
            }
        }

        if (window.addEventListener) {
            // 在现代浏览器中使用addEventListener
            window.addEventListener('message', receiveMessage, false);
        } else if (window.attachEvent) {
            // 在IE8及以下版本中使用attachEvent
            window.attachEvent('onmessage', receiveMessage);
        }
        // var operation = function () {
        //     var ajax = new $ax("/sds/sdsqcincase/delete", function (data) {
        //         layer.msg("删除成功!");
        //         SdsFillByDoctor.table.refresh();
        //     }, function (data) {
        //         layer.msg("删除失败!" + data.responseJSON.message + "!");
        //     });
        //     var params = {};
        //     params.mrListId = id;
        //     params.execUser = $("#userName").val();
        //     ajax.setData(params);
        //     ajax.start();
        // };
        // layer.confirm('是否删除病种入组病例?', {icon: 1, title: false}, function (index) {
        //     operation();
        // });
    }
};

/**
 * 单病种上报
 */
SdsFillByDoctor.upload = function (id) {
    $.messager.progress({
        title: "提示",
        msg: '正在上传数据',
        text: '上传中....'
    });
    var ajax = new $ax("/sds/sdsqcformshow/upload/" + id, function (UpRet) {
        $.messager.progress("close");
        if (UpRet.code == 1) {
            $.messager.popover({msg: '上传成功！', type: 'success', timeout: 1000})
            //更新状态
            var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '状态更新成功！', type: 'success', timeout: 1000})
                SdsFillByDoctor.search();
            }, function (data) {
                $.messager.alert("错误提示", "状态更新错误!", 'info');
            });
            // // 如果返回信息Code为“1”，且无message信息，则说明前置机该病种为测试状态，将该入组记录加个测试上报标识
            // if (UpRet.message == null || UpRet.message == "") {
            //     ax.set('testFlg', 1);
            // }
            ax.set('mrListId', id);
            ax.set('status', 'Up');
            ax.set('execUser', $("#userName").val());
            ax.start();
        } else if (UpRet.message.indexOf('重复') > -1) {
            //更新状态
            var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '已存在上传记录，状态更新成功！', type: 'success', timeout: 1000})
                SdsFillByDoctor.search();
            }, function (data) {
                $.messager.alert("错误提示", "已存在上传记录，状态更新错误!", 'info');
            });
            ax.set('mrListId', id);
            ax.set('status', 'Up');
            ax.set('execUser', $("#userName").val());
            ax.set('reason', '');
            ax.set('resume', '');
            ax.start();
        } else {
            $.messager.alert("错误提示", "表单上传失败!Error=" + UpRet.message, 'info');
        }
    }, function (data) {
        $.messager.alert("错误提示", "表单上传失败!", 'info');
    });
    ajax.setAsync();
    ajax.start();
}

/**
 * 打开查看病例操作记录
 */
SdsFillByDoctor.record = function (id, mrno, name) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        var index = layer.open({
            type: 2,
            title: '【填报审核操作日志】姓名：' + name + ' 病案号：' + mrno,
            skin: 'layer-ext-hisui',
            area: ['800px', '420px'], //宽高
            fix: false, //不固定
            content: '/sds/sdsqcincaseoperlog/' + id
        });
        this.layerIndex = index;
    }
};

SdsFillByDoctor.GetMrListIfo = function (episodeId, mrListId, name, mrNum, dishDate, stateDesc) {
    var mrlistInfo;
    var ajax = new $ax("/sds/sdsqcincase/getMrListInfo", function (data) {
        mrlistInfo = data;
    }, function () {
    });
    ajax.setData({"episodeId": episodeId});
    ajax.start();
    if (!$.isEmptyObject(mrlistInfo)) {
        var mrListId = mrlistInfo.mrlistIdOut;
        var entityIdOut = mrlistInfo.entityIdOut;
        var entityNameOut = mrlistInfo.entityNameOut;
        var entityIdIn = mrlistInfo.entityIdIn;
        var entityNameIn = mrlistInfo.entityNameIn;
        var tipsStr = "\t<p style='color:#ff7e00;background-color:#fff3dd;border: 1px solid #f7d199;text-indent:2em;'>该患者在院质控病种和出院入组筛查病种不一致，请选择并确认上报病种！</p>\n";
        tipsStr += "\t<div style='display: block;padding: 5px;'>\n"
        tipsStr += "\t<label>出院筛查病种：</label><input type=\"radio\" name=\"entityId\" value=\"" + entityIdOut + "\" checked>\n" + "<span style='color: #29723C'>" + entityNameOut + "</span>";
        tipsStr += "\t<br>\n";
        tipsStr += "\t<label>在院质控病种：</label><input type=\"radio\" name=\"entityId\" value=\"" + entityIdIn + "\">\n" + "<span style='color: #29723C'>" + entityNameIn + "</span>";
        tipsStr += "\t</div>\n";
        $("#mrListInfoHtml").html(tipsStr);
        var titleIndex = layer.open({
            type: 1,
            title: ['单病种填报提醒', 'padding-left:10px;background:#556983;color:white;'],
            content: $("#mrListInfoDiv"),
            area: ['350px', '250px'], //宽高
            fix: false, //不固定
            maxmin: false,
            skin: 'layer-ext-hisui',
            zIndex: 1100,
            btn: ['确定'],
            btnAlign: 'c',
            yes: function (index, layero) {
                layer.close(titleIndex);
                $.messager.progress({title: "提示", msg: '变更病种并自动采集填报数据', text: '采集中....'});
                SdsFillByDoctor.changeMrEntity(mrListId, $('input[name="entityId"]:checked').val());
                $.messager.progress('close');
                SdsFillByDoctor.openFormWin(mrListId, name, mrNum, dishDate, stateDesc);
            }
        });
    } else {
        SdsFillByDoctor.openFormWin(mrListId, name, mrNum, dishDate, stateDesc)
    }
};

SdsFillByDoctor.changeMrEntity = function (mrListId, entityId) {
    var ajax = new $ax("/sds/sdsqcincase/changeMrEntity", function (data) {
    }, function () {
    });
    ajax.setData({"mrListId": mrListId, "entityId": entityId});
    ajax.start();
};

// 打开表单填报窗口
SdsFillByDoctor.openFormWin = function (mrListId, name, mrNum, dishDate, state) {
    // var titleTips = "姓名:" + name + "|" + "病案号:" + mrNum + "|" + "出院日期:" + dishDate + "|" + "填报状态:" + state;
    // var index = layer.open({
    //     type: 2,
    //     title: titleTips,
    //     skin: 'layer-ext-hisui',
    //     area: ['90%', '90%'], //宽高
    //     fix: false, //不固定
    //     content: '/sds/sdsqcformshow?mrListId=' + mrListId + '&execUser=' + encodeURIComponent($("#userName").val()) + '&checkPerm=' + SdsFillByDoctor.checkPerm + '&reUploadFlag=' + (state==="上报失败"?1:0),
    //     cancel: function (index, layero) {
    //         layer.close(index);
    //         SdsFillByDoctor.table.refresh();
    //         return false;
    //     }
    // });
    // this.layerIndex = index;
    $('#p1').panel({
        noheader: true,
        border: false,
        fit: true,
        href:'/sds/sdsqcformshow?mrListId=' + mrListId + '&execUser=' + encodeURIComponent($("#userName").val()) + '&checkPerm=' + SdsFillByDoctor.checkPerm + '&reUploadFlag=' + (state==="上报失败"?1:0)
    });
}

SdsFillByDoctor.qcFormShow = function (r, e, f) {
    // 改变选中行背景色
    $('#SdsFillByDoctorTable .info').removeClass('info');//移除class
    $(e).addClass('info');//添加class
    // 未启用过程质控模块直接打开填报表单
    if (SdsFillByDoctor.enableIPQC == 'Y') {
        SdsFillByDoctor.GetMrListIfo(r.episodeId, r.id, r.name, r.mrNum, r.dishDate, r.stateDesc);
    } else {
        SdsFillByDoctor.openFormWin(r.id, r.name, r.mrNum, r.dishDate, r.stateDesc);
    }

}

$("#btnShowEntiy").on('click', function () {
    SdsFillByDoctor.search();
    $HUI.dialog('#winQCEntity').open();
    //点击返回病种列表后，应当将返回前右边的上报内容清空，以防下一次进入病种患者列表时右边直接展示上一次的上报内容
    // 获取p1元素
    var element = document.getElementById("p1");
    // 清空元素内容
    element.innerHTML = "";
});

$("#btnBatchUp").on('click', function () {
    var selectRows = $("#SdsFillByDoctorTable").bootstrapTable('getSelections');
    if (selectRows.length == 0) {
        layer.msg("请选择要上报的病例！");
        return;
    }
    $.messager.progress({
        title: "提示",
        msg: '正在上传数据',
        text: '上传中....'
    });
    var message = "";
    var successCnt = 0;
    var errorCnt = 0;
    for (var i = 0, l = selectRows.length; i < l; i++) {
        var row = selectRows[i];
        var id = row.id;
        var mrNo = row.mrNum;
        var name = row.name;
        var ajax = new $ax("/sds/sdsqcformshow/upload/" + id, function (UpRet) {
            if (UpRet.code == 1) {
                //更新状态
                var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                });
                // 如果返回信息Code为“1”，且无message信息，则说明前置机该病种为测试状态，将该入组记录加个测试上报标识
                // if (UpRet.message == null || UpRet.message == "") {
                //     ax.set('testFlg', 1);
                // }
                ax.set('mrListId', id);
                ax.set('status', 'Up');
                ax.set('execUser', $("#userName").val());
                ax.start();
                successCnt++;
            } else if (UpRet.message.indexOf('重复') > -1) {
                //更新状态
                var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                });
                ax.set('mrListId', id);
                ax.set('status', 'Up');
                ax.set('execUser', $("#userName").val());
                ax.set('reason', '');
                ax.set('resume', '');
                ax.start();
                successCnt++;
            } else {
                message += name + "(" + mrNo + ")：" + UpRet.message + "<br>";
                errorCnt++;
            }
        }, function (UpRet) {
            message += name + "(" + mrNo + ")：表单上传失败!" ;
            errorCnt++;
        });
        ajax.start();
    }
    $.messager.progress("close");

    $.messager.alert("上报结果", "成功例数："+ successCnt + " " + "错误例数：" + errorCnt + "<hr>" + message, 'info');

    SdsFillByDoctor.table.refresh();
});

/**
 * 查询病种入组病例列表
 */
SdsFillByDoctor.search = function () {
    var searchType = $('#searchType').combobox('getValue');//查询类型
    var startDate = $('#startDate').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    SdsFillByDoctor.getQcincaseByDate(searchType, startDate, endDate)
};

/**
 * 按条件数据查询
 */
SdsFillByDoctor.getQcincaseByDate = function (searchType, startDate, endDate) {
    //加载病种显示
    var ajax = new $ax("/api/fillByDoctor/qryQCEntity", function (data) {
        //查询报告份数渲染
        var num = data.patientNum;
        delete data.patientNum;
        $("#entityNum").html(num);
        SdsFillByDoctor.drawEntityDetail(data);
        SdsFillByDoctor.drawCharts(data,"entityNoReportChart");
    }, function (data) {
        layer.msg("查询失败！");
        return false;
    });
    var params = {};
    params.searchType = searchType;
    params.startDate = startDate;
    params.endDate = endDate;
    params.locId = $("#locId").val();
    params.docName=SdsFillByDoctor.docName;
    params.dimType= "entity";
    ajax.setData(params);
    ajax.start();

    //加载医师显示
    var ajax = new $ax("/api/fillByDoctor/qryQCEntity", function (data) {
        SdsFillByDoctor.drawCharts(data,"docNoReportChart");
    }, function (data) {
        layer.msg("查询失败！");
        return false;
    });
    var params = {};
    params.searchType = searchType;
    params.startDate = startDate;
    params.endDate = endDate;
    params.locId = $("#locId").val();
    params.docName=SdsFillByDoctor.docName;
    params.dimType= "doctor";
    ajax.setData(params);
    ajax.start();
}

/**
 * 组装病种填报数据
 */
SdsFillByDoctor.drawEntityDetail = function (data) {
    var listHtml = "<div style='padding:10px;'>";
    var entityNum = 0;
    for (var key in data) {
        entityNum++;
        var entityDetail = data[key];
        var divClz="";
        if (entityDetail.isActive == 3) {divClz='divMask'}
        listHtml += " <div class='"+divClz+"' style='background:#eff5ff;border:1px solid #ccc;padding:5px;margin-bottom: 10px;float:left;width:100%; border-radius: 5px;'>";
        listHtml += " <div><img style='float: left;border-radius: 10px;' width='50px'  height='50px' src='/static/common/img/sds/" + key + ".png'/></div>";
        listHtml += " <div style='float: left'>";
        if (entityDetail.isActive == 2) { // 测试病种标识
            if (entityDetail.testCount >= 20) {
                listHtml += " <p style='margin: 5px 0 5px 15px;font-weight: bold;'>" + entityDetail.btDesc + "&nbsp;<img src='/static/common/img/sds/test.png'>&nbsp;<span style='color: #ff0000'>测试病种，已上报超20例！</span></p>";
            } else {
                listHtml += " <p style='margin: 5px 0 5px 15px;font-weight: bold;'>" + entityDetail.btDesc + "&nbsp;<img src='/static/common/img/sds/test.png'></p>";
            }
        } else {
            listHtml += " <p style='margin: 5px 0 5px 15px;font-weight: bold;'>" + entityDetail.btDesc + "</p>";
        }
        listHtml += " <div style='float: left;margin-left: 15px;width: 100px;'>";
        listHtml += " <p style='margin:0 0 5px 0;'>待填报：<a style='cursor:pointer' onClick='SdsFillByDoctor.LoadItemSta(\"" + entityDetail.entityId + "\",\"" + entityDetail.btDesc + "\",\"notReported\")'><span>" + entityDetail.notReported + "</span></a></p>";
        listHtml += " </div>";
        if (SdsFillByDoctor.docUpPerm !== "Y") {
            listHtml += " <div style='float: left;margin-left: 15px;width: 100px;'>";
            listHtml += " <p style='margin:0 0 5px 0;'>已退回：<a style='cursor:pointer' onClick='SdsFillByDoctor.LoadItemSta(\"" + entityDetail.entityId + "\",\"" + entityDetail.btDesc + "\",\"backed\")'><span>" + entityDetail.backed + "</span></a></p>";
            listHtml += " </div>";
            listHtml += " <div style='float: left;margin-left: 15px;width: 100px;'>";
            listHtml += " <p style='margin:0 0 5px 0;'>待审核：<a style='cursor:pointer' onClick='SdsFillByDoctor.LoadItemSta(\"" + entityDetail.entityId + "\",\"" + entityDetail.btDesc + "\",\"notChecked\")'><span>" + entityDetail.notChecked + "</span></a></p>";
            listHtml += " </div>";
            listHtml += " <div style='float: left;margin-left: 15px;width: 100px;'>";
            listHtml += " <p style='margin:0 0 5px 0;'>已审核：<a style='cursor:pointer' onClick='SdsFillByDoctor.LoadItemSta(\"" + entityDetail.entityId + "\",\"" + entityDetail.btDesc + "\",\"checked\")'><span>" + entityDetail.checked + "</span></a></p>";
            listHtml += " </div>";
        }
        listHtml += " <div style='float: left;margin-left: 15px;width: 100px;'>";
        listHtml += " <p style='margin:0 0 5px 0;'>已上报：<a style='cursor:pointer' onClick='SdsFillByDoctor.LoadItemSta(\"" + entityDetail.entityId + "\",\"" + entityDetail.btDesc + "\",\"reported\")'><span>" + entityDetail.reported + "</span></a></p>";
        listHtml += " </div>";
        listHtml += " <div style='float: left;margin-left: 15px;width: 100px;'>";
        listHtml += " <p style='margin:0 0 5px 0;'>上报成功：<a style='cursor:pointer' onClick='SdsFillByDoctor.LoadItemSta(\"" + entityDetail.entityId + "\",\"" + entityDetail.btDesc + "\",\"uploadSuccess\")'><span>" + entityDetail.uploadSuccess + "</span></a></p>";
        listHtml += " </div>";
        listHtml += " <div style='float: left;margin-left: 15px;width: 100px;'>";
        listHtml += " <p style='margin:0 0 5px 0;'>上报失败：<a style='cursor:pointer' onClick='SdsFillByDoctor.LoadItemSta(\"" + entityDetail.entityId + "\",\"" + entityDetail.btDesc + "\",\"uploadFailure\")'><span>" + entityDetail.uploadFailure + "</span></a></p>";
        listHtml += " </div>";
        listHtml += "</div>";
        listHtml += "</div>";
        listHtml += "<div style='clear:both'></div>"
    }
    if (entityNum == 0) {
        listHtml = "<div style='height: 250px;padding:10px;text-align:center;'>";
        listHtml += " <img width='30%' height='200px' src='/static/common/img/nodata.png'/>";
    }
    listHtml += " </div>";
    $('#QCEntityList').html(listHtml);
    /*$.parser.parse('#QCEntityList');  //解析checkbox*/
}

/**
 * 绘制下方病种图表
 * @param searchType
 * @param startDate
 * @param endDate
 */
SdsFillByDoctor.drawCharts = function (data,elementId) {

    var dataobj = []
    for (var key in data) {
        var entityDetail = data[key];
        if (entityDetail.notReported==undefined) continue;
        var tobj = new Object()
        tobj.value = entityDetail.notReported;
        tobj.name = key;
        if (elementId == "entityNoReportChart") {
            //按病种展示 记录病种id  方便展示病种未报明细
            tobj.entityInfo = (entityDetail.entityId +"^"+ entityDetail.btDesc);
        }
        dataobj.push(tobj)
    }
    dataobj.sort(function(a, b){return b.value - a.value});

    var xdata = []
    var ydata = []
    dataobj.forEach(function(item,index){
        xdata.push(item.name);
        ydata.push(item.value);
        if (elementId == "entityNoReportChart") {
            //按病种展示 记录病种id  方便展示病种未报明细
            SdsFillByDoctor.entityArray.push(item.entityInfo);
        }

    });

    var NoReportChart = echarts.init(document.getElementById(elementId));    //待上报例数图表

    var option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'line'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '8%',
            containLabel: true
        },
        legend: {
            data:['待填报数']
        },
        xAxis: [
            {
                name: '',
                type: 'category',

                axisLabel: {
                    interval: 0,
                },
                data: xdata
            },
        ],
        yAxis: [
            {
                name: '病例数1',
                type: 'value',
                minInterval: 1, //设置成1保证坐标轴分割刻度显示成整数。
            }
        ],
        series: [
            {
                name:'数量',
                type: 'bar',

                stack: '待填报',
                data: ydata
            }
        ]
    };

    // 使用刚指定的配置项和数据显示图表。
    NoReportChart.setOption(option);
    NoReportChart.on('click', function(params) {
        let entityId = "",entitydesc = "",docName=""
        let entityInfo;
        if (elementId == "entityNoReportChart") {
            entityInfo = SdsFillByDoctor.entityArray[params.dataIndex];
            entityId = entityInfo.split("^")[0];
            entitydesc = entityInfo.split("^")[1];
        } else {
            SdsFillByDoctor.docName = params.name;
        }

        SdsFillByDoctor.LoadItemSta(entityId,entitydesc,"notReported");
    });
}
/**
 * 钻取填报数字
 * @param QCEntiyID
 * @param QCEntiyDesc
 * @param status
 * @constructor
 */
SdsFillByDoctor.LoadItemSta = function (QCEntiyID, QCEntiyDesc, status) {
    var searchType = $('#searchType').combobox('getValue');
    var startDate = $('#startDate').datebox('getValue');//开始日期
    var endDate = $('#endDate').datebox('getValue');//结束日期

    $('#entityName').panel({title: '<span style="float: left;">' + QCEntiyDesc+ '</span>' +
            '<span style="padding-left:10px;float:left;color:#1474AF;"><span className="icon icon-tip" style="margin-right:5px;">&nbsp;&nbsp;&nbsp;&nbsp;</span>提示信息：请双击行记录，打开单病种表单！</span>'});

    SdsFillByDoctor.loadTableData(searchType, startDate, endDate, QCEntiyID, status);

    $HUI.dialog('#winQCEntity').close();
}

$(function () {

    $('#winQCEntity').dialog({
        title: '病种统计',
        closable: false,
        modal: true
    });
    //var opt = $("#startDate").datebox('options');
    //opt.minDate = '2022-01-01';
    // 查询病种填报及各指标数据
    SdsFillByDoctor.search();

    // 患者列表
    var defaultColunms = SdsFillByDoctor.initColumn();
    var table = new BSTable(SdsFillByDoctor.id, "/api/fillByDoctor/list", defaultColunms);
    table.setPaginationType("server");
    table.setPageSize(20);
    table.setSortOrder('desc');
    table.setSortName('dishDate');
    table.setShowRefresh(false);
    table.setShowColumns(false);
    table.setShowToggle(false);
    table.setShowExport(false);
    var b_height = document.documentElement.clientHeight;
    table.setHeight(b_height - 28);
    table.setOnDblClickRow(SdsFillByDoctor.qcFormShow); //双击数据行打开表单填报
    SdsFillByDoctor.table = table.init();

    /* 如果医生不能直接上报，则隐藏批量上报按钮*/
    if (SdsFillByDoctor.docUpPerm !== 'Y') {
        $("#btnBatchUp").hide();
    } else {
        $("#btnBatchUp").show();
    }
});

/**
 * 计算与当前时间的时间差（天）
 */
function diffTimeWithNow(time, compareTime) {
    var compare_date = compareTime
        ? new Date(compareTime.replace(/-/g, '/')) // 替换并尝试创建Date对象
        : new Date(); // 如果compareTime为空，使用当前时间
    if (time == "") {
        return "";
    }

    var old_date = new Date( time = time.replace(/-/g, '/'));
    var diff_time = (compare_date - old_date) / 1000; //计算时间差,并把毫秒转换成秒
    var days = parseInt(diff_time / 86400);
    return days;
}

function changeDoc(obj) {
    if (obj.value) {
        SdsFillByDoctor.docName="";
        SdsFillByDoctor.search();
    } else {
        SdsFillByDoctor.docName=$("#userName").val();
        SdsFillByDoctor.search();
    }
}
